#include <vector>
#include <unordered_map>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
/*
 * @lc app=leetcode.cn id=105 lang=cpp
 *
 * [105] 从前序与中序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // 递归解法
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        unordered_map<int, int> mapper;
        // 映射mapper的值和坐标关系
        for (int i = 0; i < inorder.size(); i++) mapper.insert({inorder[i], i}); 
        return buildTreeHelper(mapper, preorder, inorder, 0, inorder.size() - 1, 0, preorder.size() - 1);
    }


    TreeNode* buildTreeHelper(unordered_map<int, int>& mapper, vector<int>& preorder, vector<int>& inorder, int ip, int ie, int pp, int pe)  {
        if (pp > pe) return nullptr;
        TreeNode *now = new TreeNode(preorder[pp]);
        int index = mapper[preorder[pp]];
        int lz = index - ip, rz = ie - index;
        now->left = buildTreeHelper(mapper, preorder, inorder, ip, index - 1, pp + 1, pp + lz);
        now->right = buildTreeHelper(mapper, preorder, inorder, index + 1, ie, pp + lz + 1, pp + lz + rz);
        return now;
    }

    // TODO: 迭代解法
};
// @lc code=end

